package net.oschina.git.hikoyan.helloapi.async;

import net.oschina.git.hikoyan.helloapi.common.Config;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.*;

/**
 * Created by yan on 17/2/14.
 */
public class ThreadPoolManager {

    private final Config config;
    private ExecutorService postExecutor;
    private final BlockingQueue<Runnable> postThreadPoolQueue;

    public void initialize() {
        postExecutor = new ExtendedExecutor(
                this.config.getPostThreadPoolNums(),
                this.config.getPostThreadPoolNums(),
                1000 * 60,
                TimeUnit.MILLISECONDS,
                this.postThreadPoolQueue,
                new ThreadFactoryImpl("PostThread_"));
    }

    public ThreadPoolManager(final Config config) {
        this.config = config;
        this.postThreadPoolQueue =
                new LinkedBlockingQueue<Runnable>(this.config.getSendThreadPoolQueueCapacity());

    }

    public void addExecuteTask(Runnable task) {
        if (postExecutor != null) {
            postExecutor.submit(task);
        }
    }

    public void executeDeferredResult(String result, DeferredResult<String> deferredResult) {

        deferredResult.setResult(result);
    }

    public void shutdown() {
        if (postExecutor != null) {
            postExecutor.shutdown();
        }
    }

    public Executor getExecutor() {
        return postExecutor;
    }
}
